#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include <sys/stat.h>
#include<dirent.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>


void LS(char* dir_name);

int
main(int argc, char* args[])
{
	if(argc == 1){
		LS(".");
	}
	else if(argc == 2){
		LS(args[1]);
	}
	else{
		perror("args error");
		exit(1);
	}

	exit(0);
}

//LS only work in dir
void LS(char* dir_name)
{
	DIR* dp;
	dp = opendir(dir_name);
	if(!dp){
		perror("open dir error");
		exit(1);
	}

	struct dirent* det;
	
	errno = 0;
	while(det = readdir(dp))
	{
		//char dname[256] = det -> d_name;

		//if path is ".." || ".",can't LS the path;
		if(strcmp(det -> d_name, ".") == 0 || strcmp(det -> d_name, "..") == 0)
		continue;

		char path[256];
		sprintf(path, "%s/%s", dir_name, det -> d_name);

		struct stat stbuf;

		if(stat(path, &stbuf) < 0){
			printf("path is %s\n",path);
			perror("get path stat error");
			exit(1);
		}

		//if path is to dir
		if( S_ISDIR(stbuf.st_mode) ){
			LS(path);
		}
		//path is note dir
		else{
			printf("%*s | %*d\n", -40 ,det -> d_name, -12, stbuf.st_size);
		}

		errno = 0;
	}

	if(errno) perror("readdir error");

	return;

}